package com.guaoran.distributed.io.nio.one.channel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author gucheng
 * @Description FileChannel
 * 2019-04-19 14:43
 */
public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
        String fileName = "F:\\test.txt";
        readFile(fileName);
        System.out.println("\n=============================");
        writeFile(fileName);
        readFile(fileName);
    }

    public static void writeFile(String fileName) throws IOException {
        byte [] content = {83, 111, 109, 101, 32, 98, 121, 116, 101, 115, 46};
        FileOutputStream fos = new FileOutputStream(fileName,true);
        FileChannel channel = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.wrap(content);
        channel.write(buffer);
        channel.close();
        fos.flush();
        fos.close();
    }

    public static void readFile(String fileName) throws IOException{
        FileInputStream fis = new FileInputStream(fileName);
        // 获得一个通道
        FileChannel fileChannel = fis.getChannel();
        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int read = fileChannel.read(buffer);
        buffer.flip();
        while(buffer.hasRemaining()){
            System.out.print((char)(buffer.get()));
        }
        fileChannel.close();
        fis.close();
    }
}
